//
//  ImageTableViewController.m
//  WildDonkeySectionOne
//
//  Created by 黎传炎 on 15/3/28.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "ImageTableViewController.h"
#import "BJTableViewCell.h"
#import "BJData.h"
#import "UIImageView+WebCache.h"
#import "EntertainmentTableViewController.h"
#import "DVSwitch.h"
#import "MJRefresh.h"

@interface ImageTableViewController ()
//@property (nonatomic,retain)UIActivityIndicatorView *activity;
@property (nonatomic,retain)NSMutableData *receivedData;//拼接新数据
@property (nonatomic,retain)NSMutableArray *aCtivitiesArray;
//@property (nonatomic,assign)NSInteger page;
@end
static NSInteger _page = 1;
@implementation ImageTableViewController

- (void)dealloc
{
    [_cell release];
    //[_activity release];
    [_receivedData release];
    [_aCtivitiesArray release];
    [super dealloc];
}

- (void)SelectSeg:(UISegmentedControl *)number
{
    EntertainmentTableViewController *entVC = [[EntertainmentTableViewController alloc]init];
    if (number.selectedSegmentIndex == 1) {
        [self.navigationController pushViewController:entVC animated:YES];
    }
    
}

-(void)setTitleSegment
{
    UISegmentedControl *segmentedControl=[[UISegmentedControl alloc] initWithFrame:CGRectMake(80.0f, 8.0f, 150.0f, 30.0f) ];
    [segmentedControl insertSegmentWithTitle:@"图文" atIndex:0 animated:YES];
    [segmentedControl insertSegmentWithTitle:@"视频" atIndex:1 animated:YES];
    segmentedControl.momentary = YES;
    segmentedControl.multipleTouchEnabled=NO;
    [segmentedControl addTarget:self action:@selector(SelectSeg:) forControlEvents:UIControlEventValueChanged];
    [self.navigationItem setTitleView:segmentedControl];
}

//接到回应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if (self.aCtivitiesArray.count != 0) {
        
    }else {
        
        self.aCtivitiesArray = [NSMutableArray array];
        
    }
    
    self.receivedData = [NSMutableData data];
    
}
//服务器多次返回数据的方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    [self.receivedData appendData:data];
    
}
//下载完毕结束的时候
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.receivedData options:NSJSONReadingMutableContainers error:nil];
    NSDictionary *array = [dic objectForKey:@"list"];
    
    for (NSDictionary *dic in array) {
        BJData *bjdata = [[BJData alloc]init];
        [bjdata setValuesForKeysWithDictionary:dic];
        [self.aCtivitiesArray addObject:bjdata];
        [bjdata release];
        
    }
    
    //    if (self.aCtivitiesArray.count > 0) {
    //        self.aCtivitiesArray arrayByAddingObjectsFromArray:_aCtivitiesArray];
    //    }
    
    [self.tableView reloadData];//相当于刷新
    //[_activity stopAnimating];
}
//请求超时 有错误等等执行的方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@",error);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitleSegment];
    
    [self setupRefreshView];//调用自动刷新
}

- (void)setupRefreshView
{
    //设置头部刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(addLegendHeaderWithRefreshing) dateKey:nil];
    
    [self.tableView.header beginRefreshing];//进入程序就执行刷新
    //设置上拉加载数据
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(addLegendFooterWithRefreshing)];
}

- (void)addLegendHeaderWithRefreshing
{
    int x= 205;
    NSString *str = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=93E4AE6F-8ACB-4B08-A321-4633543F6F9E&c=data&client=iphone&device=iPhone%x&from=ios&jbk=0&mac=&market=&openudid=e0382b752bef59df89921d75a689d93f1c4cc5e7&page=0&per=20&type=10&udid=&ver=3.2",x];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    [self.tableView reloadData];
    [self.tableView.header endRefreshing];
}

- (void)addLegendFooterWithRefreshing
{
    _page = _page + 1;
    NSInteger x= 205;
    NSString *str = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=93E4AE6F-8ACB-4B08-A321-4633543F6F9E&c=data&client=iphone&device=iPhone%ld&from=ios&jbk=0&mac=&market=&openudid=e0382b752bef59df89921d75a689d93f1c4cc5e7&page=%ld&per=10&type=10&udid=&ver=3.2",(long)x,(long)_page];
    
    NSURL *url = [NSURL URLWithString:str];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    [self.tableView reloadData];
    
    [self.tableView.footer endRefreshing];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Potentially incomplete method implementation.
//    // Return the number of sections.
//    return [self.aCtivitiesArray count];
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.aCtivitiesArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat aa = [UIScreen mainScreen].bounds.size.width;
    BJData * DataHeight = self.aCtivitiesArray[indexPath.row];
    
    if (DataHeight.width >= aa) {
        return  _cell.height + [BJTableViewCell heightForString:DataHeight.text] + 80;
    }
    return DataHeight.height + [BJTableViewCell heightForString:DataHeight.text] + 80;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reusable = @"reus";
    
    _cell = [tableView dequeueReusableCellWithIdentifier:reusable];
    
    if (nil == _cell) {
        _cell = [[BJTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusable];
        
    }
    _cell.bjdata = self.aCtivitiesArray[indexPath.row];
    
    // Configure the cell...
    
    return _cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
